﻿using ESoft.Core.Logging;
using ESoft.Core.Web.VO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace ESoft.Core.Web.Common.Filters
{
    public class HttpGlobalExceptionFilter : IExceptionFilter
    {
        readonly IHostingEnvironment _env;

        public HttpGlobalExceptionFilter(IHostingEnvironment env)
        {
            _env = env;
        }

        public void OnException(ExceptionContext context)
        {
            var logger = LogManager.GetLogger(context.Exception.TargetSite.ReflectedType);
            logger.Error(context.Exception);
            context.Result = new ApplicationErrorResult(ResponseResult.FailOut(context.Exception));
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.ExceptionHandled = true;
        }

        public class ApplicationErrorResult : ObjectResult
        {
            public ApplicationErrorResult(object value) : base(value)
            {
                StatusCode = (int)HttpStatusCode.OK;
            }
        }
    }
}
